<template>
  <div class="register">
    <Particles
        id="tsparticles"
        :particlesInit="particlesInit"
        :particlesLoaded="particlesLoaded"
        :options="particles3"
    />
    <!--  Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可  -->
    <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
      <h2 class="title">{{ $t('login.title') }}</h2>
      <lang-select style="margin-bottom: 15px"/>
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="步骤 1" description="编辑你的账号密码"></el-step>
        <el-step title="步骤 2" description="进行你的个性化定制"></el-step>
        <el-step title="步骤 3" description="选择一个帅气的头像"></el-step>
      </el-steps>
      <div v-show="active === 0">
        <el-form-item prop="username">
          <el-input
              v-model="registerForm.username"
              type="text"
              size="large"
              auto-complete="off"
              :placeholder="$t('login.username')"
          >
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              size="large"
              auto-complete="off"
              :placeholder="$t('login.password')"
              @keyup.enter="handleRegister"
          >
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              size="large"
              auto-complete="off"
              :placeholder="$t('login.confirm')"
              @keyup.enter="handleRegister"
          >
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
      </div>
      <div v-show="active === 1">
        <el-form-item prop="sex" label="性 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别">
          <el-radio-group v-model="registerForm.sex" style="margin-left: 4px">
            <el-radio label="男">
              <svg-icon
                style="width: 1.3em;height: 1.3em;"
                icon-class="man" /> 男
            </el-radio>
            <el-radio label="女">
              <svg-icon
                  style="width: 1.6em;height: 1.6em;margin-top: 0.2em"
                  icon-class="woman" /> 女
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="hobby" label="爱 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;好">
          <el-checkbox-group v-model="registerForm.hobby" style="margin-left: 4px">
            <el-checkbox label="Java"></el-checkbox>
            <el-checkbox label="Web"></el-checkbox>
            <el-checkbox label="Python"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="birth" label="出生日期">
          <el-date-picker
              v-model="registerForm.birth"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </div>
      <div v-show="active === 2">
        <el-form-item prop="birth" label="上传头像" style="margin-top: 30px">
          <div class="text-center" style="margin-top: -15px">
            <RegisterAvatar />
          </div>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
              size="large"
              v-model="registerForm.code"
              auto-complete="off"
              :placeholder="$t('login.verification')"
              style="width: 63%"
              @keyup.enter="handleRegister"
          >
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="register-code">
            <img :src="codeUrl" @click="getCode" class="register-code-img"/>
          </div>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width:100%;"
              @click.prevent="testRegister"
          >
            <span v-if="!loading">{{ $t('register.register') }}</span>
            <span v-else>{{ $t('register.registering') }}</span>
          </el-button>
        </el-form-item>
      </div>
      <el-row>
        <!-- TODO 当前页校验成功后才可以继续编辑-->
        <el-col :span="12"><el-button type="primary" style="margin-left: 0px;" @click=active-- :disabled="active === 0"><svg-icon icon-class="back" class="el-input__icon input-icon" />&nbsp;上一步</el-button>
        </el-col>
        <el-col :span="12"><el-button type="primary" style="margin-left: 83px;" @click=active++ :disabled="active === 2">下一步&nbsp;<svg-icon icon-class="next" class="el-input__icon input-icon" /></el-button>
        </el-col>
      </el-row>
      <el-form-item style="width:100%;">
        <div style="margin-top: 10px" :class="language">
          <router-link class="link-type" :to="'/login'">{{ $t('login.existLogin') }}</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2018-2023.</span>
    </div>
  </div>
</template>

<script setup>
import { ElMessageBox } from "element-plus";
import { getCodeImg, register } from "@/api/login";
//背景动画
import { particles,particles2,particles3,particles4,particles5,particles6 } from '../components/Particles/particles.js'
import { loadFull } from "tsparticles";
import LangSelect from '@/components/LangSelect'
import {computed} from "vue";
import { useI18n } from 'vue-i18n'
import useI18NStore from "@/store/modules/i18n";
import RegisterAvatar from "@/components/Wind/RegisterAvatar";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const i18nStore = useI18NStore()
const { t } = useI18n()

//粒子效果
const particlesInit = async engine => {
  await loadFull(engine);
};
const particlesLoaded = async container => {
  console.log("Particles container loaded", container);
};

const router = useRouter();
const { proxy } = getCurrentInstance();

const language = computed(()=> {
  //return this.$store.getters.language
  return i18nStore.language
})

// 步骤
const active = ref(0)

// 注册表单 获取自pinia库
const registerForm = computed(()=> {
  return userStore.registerForm
})

const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error(t('register.errorPwd')));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    { required: true, trigger: "blur", message: t('register.account') },
    { min: 2, max: 20, message: t('register.accountMessage'), trigger: "blur" }
  ],
  password: [
    { required: true, trigger: "blur", message: t('register.password') },
    { min: 5, max: 20, message: t('register.passwordMessage'), trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: t('register.passwordAgain') },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ],
  code: [{ required: true, trigger: "change", message: t('register.verification') }]
};

const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);

// 正式版注册按钮
function handleRegister() {
  proxy.$refs.registerRef.validate(valid => {
    if (valid) {
      loading.value = true;
      active.value ++;
      register(registerForm.value).then(res => {
        const username = registerForm.value.username;
        ElMessageBox.alert("<font color='green'>"+ t('register.congratulations')  + " [ " + username + " ] " + t('register.success') + "！</font>", t('register.alert'), {
          dangerouslyUseHTMLString: true,
          type: "success",
        }).then(() => {
          router.push("/login");
        }).catch(() => {});
      }).catch(() => {
        loading.value = false;
        active.value ++;
        if (captchaEnabled) {
          getCode();
        }
      });
    }
  });
}

// 测试版注册按钮
function testRegister(){
  //console.log(registerForm.value)
  alert(JSON.stringify(registerForm.value))
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      registerForm.value.uuid = res.uuid;
    }
  });
}

getCode();
</script>

<style lang='scss' scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 40px;
  padding-left: 12px;
}
.en {
  margin-left: 159px;
}
.zh {
  margin-left: 68%;
}
</style>
